package top.wilsonlv.jaguar.cloud.upms.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import top.wilsonlv.jaguar.basecrud.BaseController;
import top.wilsonlv.jaguar.cloud.upms.controller.vo.UserDeviceVO;
import top.wilsonlv.jaguar.cloud.upms.entity.UserDevice;
import top.wilsonlv.jaguar.cloud.upms.mapper.UserDeviceMapper;
import top.wilsonlv.jaguar.cloud.upms.sdk.dto.DeviceBindDTO;
import top.wilsonlv.jaguar.cloud.upms.service.DeviceService;
import top.wilsonlv.jaguar.cloud.upms.service.UserDeviceService;
import top.wilsonlv.jaguar.commons.web.response.JsonResult;
import top.wilsonlv.jaguar.commons.web.util.WebUtil;
import top.wilsonlv.jaguar.security.util.SecurityUtil;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lvws
 * @since 2022/1/13
 */
@RestController
@RequestMapping("/personal/device")
@RequiredArgsConstructor
@Api(tags = "当前登录用户设备API")
public class PersonalDeviceApi extends BaseController<UserDevice, UserDeviceMapper, UserDeviceService> {

    private final DeviceService deviceService;


    @ApiOperation(value = "获取设备")
    @GetMapping("/page")
    public JsonResult<Page<UserDeviceVO>> page(@ApiIgnore Page<UserDevice> page) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityUtil.getCurrentUserId());
        return JsonResult.success(service.queryUserDevice(page, params));
    }

    @ApiOperation(value = "绑定设备")
    @PostMapping("/bindDevice")
    public JsonResult<Void> bindDevice(@Valid @RequestBody DeviceBindDTO bindDTO,
                                       @RequestParam(required = false) String sign,
                                       @RequestParam(required = false) String nonce,
                                       @RequestParam(required = false) Long timestamp,
                                       HttpServletRequest request) {

        deviceService.bindDevice(SecurityUtil.getCurrentUserId(), WebUtil.getHost(), bindDTO,
                timestamp, nonce, sign, request.getParameterMap());
        return JsonResult.success();
    }

    @ApiOperation(value = "解绑设备")
    @DeleteMapping("/unbindDevice/{deviceUid}")
    public JsonResult<Void> unbindDevice(@PathVariable String deviceUid) {
        service.unbindDevice(SecurityUtil.getCurrentUserId(), deviceUid);
        return success();
    }

}
